<!--
  提现管理主页面
  @description 提现管理的列表页面，包含搜索、表格、分页、操作等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="-mb-15px"
    >
      <el-form-item :label="t('settle.withdraw.withdrawNo')" prop="withdrawNo">
        <el-input
          v-model="queryParams.withdrawNo"
          :placeholder="t('settle.common.pleaseInput') + t('settle.withdraw.withdrawNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.withdraw.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('settle.common.pleaseInput') + t('settle.withdraw.merchantNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.withdraw.withdrawStatus')" prop="withdrawStatus">
        <el-select
          v-model="queryParams.withdrawStatus"
          :placeholder="t('settle.common.pleaseSelect') + t('settle.withdraw.withdrawStatus')"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="(label, value) in withdrawStatusOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('settle.withdraw.applyTime')" prop="applyTime">
        <el-date-picker
          v-model="queryParams.applyTime"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="t('settle.common.startTime')"
          :end-placeholder="t('settle.common.endTime')"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('settle.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('settle.common.reset') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['settle:withdraw:export']"
        >
          <Icon class="mr-5px" icon="ep:download" />
          {{ t('settle.common.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column
        :label="t('settle.withdraw.withdrawNo')"
        align="center"
        prop="withdrawNo"
        width="200"
      />
      <el-table-column
        :label="t('settle.withdraw.merchantNo')"
        align="center"
        prop="merchantNo"
        width="180"
      />
      <el-table-column
        :label="t('settle.withdraw.merchantName')"
        align="center"
        prop="merchantName"
        min-width="150"
      />
      <el-table-column
        :label="t('settle.withdraw.withdrawAmount')"
        align="center"
        prop="withdrawAmount"
        width="120"
      >
        <template #default="scope">
          <span class="amount-text">¥{{ (scope.row.withdrawAmount / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.withdraw.feeAmount')"
        align="center"
        prop="feeAmount"
        width="100"
      >
        <template #default="scope">
          <span class="fee-text">¥{{ (scope.row.feeAmount / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.withdraw.actualAmount')"
        align="center"
        prop="actualAmount"
        width="120"
      >
        <template #default="scope">
          <span class="actual-text">¥{{ (scope.row.actualAmount / 100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.withdraw.withdrawStatus')"
        align="center"
        prop="withdrawStatus"
        width="100"
      >
        <template #default="scope">
          <el-tag :type="getWithdrawStatusTagType(scope.row.withdrawStatus)">
            {{ withdrawStatusOptions[scope.row.withdrawStatus] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.withdraw.bankName')"
        align="center"
        prop="bankName"
        width="120"
      />
      <el-table-column
        :label="t('settle.withdraw.bankAccount')"
        align="center"
        prop="bankAccount"
        width="150"
      >
        <template #default="scope">
          {{ maskBankAccount(scope.row.bankAccount) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.withdraw.applyTime')"
        align="center"
        prop="applyTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column
        :label="t('settle.common.operation')"
        align="center"
        width="200"
        fixed="right"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row)"
            v-hasPermi="['settle:withdraw:query']"
          >
            {{ t('settle.common.view') }}
          </el-button>
          <el-button
            link
            type="success"
            @click="handleApprove(scope.row)"
            v-hasPermi="['settle:withdraw:approve']"
            v-if="scope.row.withdrawStatus === WithdrawStatusEnum.PENDING"
          >
            {{ t('settle.withdraw.approve') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleReject(scope.row)"
            v-hasPermi="['settle:withdraw:reject']"
            v-if="scope.row.withdrawStatus === WithdrawStatusEnum.PENDING"
          >
            {{ t('settle.withdraw.reject') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 提现详情 -->
  <WithdrawDetail ref="detailRef" />

  <!-- 审核对话框 -->
  <WithdrawAuditDialog ref="auditDialogRef" @success="getList" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import { getWithdrawApplyPageApi, exportWithdrawApplyApi } from '@/api/settle/withdraw'
import type { WithdrawVO, WithdrawPageReqVO } from '@/api/settle/types'
import { WithdrawStatusEnum } from '@/api/settle/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import WithdrawDetail from './WithdrawDetail.vue'
import WithdrawAuditDialog from './WithdrawAuditDialog.vue'

defineOptions({ name: 'SettleWithdraw' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(true)
const exportLoading = ref(false)

// 列表数据
const list = ref<WithdrawVO[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<WithdrawPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  withdrawNo: undefined,
  merchantNo: undefined,
  withdrawStatus: undefined,
  applyTime: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const detailRef = ref()
const auditDialogRef = ref()

// 选项数据
const withdrawStatusOptions = {
  [WithdrawStatusEnum.PENDING]: t('settle.withdraw.withdrawStatuses.pending'),
  [WithdrawStatusEnum.APPROVED]: t('settle.withdraw.withdrawStatuses.approved'),
  [WithdrawStatusEnum.REJECTED]: t('settle.withdraw.withdrawStatuses.rejected'),
  [WithdrawStatusEnum.PROCESSING]: t('settle.withdraw.withdrawStatuses.processing'),
  [WithdrawStatusEnum.SUCCESS]: t('settle.withdraw.withdrawStatuses.success'),
  [WithdrawStatusEnum.FAILED]: t('settle.withdraw.withdrawStatuses.failed')
}

/**
 * 查询列表
 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getWithdrawApplyPageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询提现列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/**
 * 查看详情
 */
const openDetail = (row: WithdrawVO) => {
  detailRef.value.open(row)
}

/**
 * 审核通过
 */
const handleApprove = (row: WithdrawVO) => {
  auditDialogRef.value.open(row, 'approve')
}

/**
 * 审核拒绝
 */
const handleReject = (row: WithdrawVO) => {
  auditDialogRef.value.open(row, 'reject')
}

/**
 * 导出按钮操作
 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportWithdrawApplyApi(queryParams)
    message.success(t('settle.common.exportSuccess'))
  } catch (error) {
    console.error('导出提现数据失败:', error)
  } finally {
    exportLoading.value = false
  }
}

/**
 * 银行账号脱敏
 */
const maskBankAccount = (account: string) => {
  if (!account || account.length < 8) return account
  return account.substring(0, 4) + '****' + account.substring(account.length - 4)
}

// 标签类型获取函数
const getWithdrawStatusTagType = (status: number) => {
  const statusMap = {
    [WithdrawStatusEnum.PENDING]: 'warning',
    [WithdrawStatusEnum.APPROVED]: 'primary',
    [WithdrawStatusEnum.REJECTED]: 'danger',
    [WithdrawStatusEnum.PROCESSING]: 'info',
    [WithdrawStatusEnum.SUCCESS]: 'success',
    [WithdrawStatusEnum.FAILED]: 'danger'
  }
  return statusMap[status] || ''
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style scoped>
.amount-text {
  color: #409eff;
  font-weight: bold;
}

.fee-text {
  color: #e6a23c;
  font-weight: bold;
}

.actual-text {
  color: #67c23a;
  font-weight: bold;
  font-size: 16px;
}
</style>
